package controllers

import (
	"demo/response"
	"demo/services"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

func Register(c *gin.Context) {
	//接收参数
	// json_data, _ := c.GetRawData()
	//反序列化
	// var param map[string]string
	// json.Unmarshal(json_data, &param)
	var result *response.Response
	//验证参数是否正确
	// user_name, ok := param["user_name"]
	// if !ok {
	// 	result = response.Err(response.SERVER_ERROR, []string{"缺少必要参数user_name"})
	// 	c.JSON(200, result)
	// 	return
	// }
	// password, ok := param["password"]
	// if !ok {
	// 	result = response.Err(response.SERVER_ERROR, []string{"缺少必要参数pasword"})
	// 	c.JSON(200, result)
	// 	return
	// }
	// if len(user_name) < 5 || len(user_name) > 20 {
	// 	result = response.Err(response.SERVER_ERROR, []string{"用户名必须5-20不包含"})
	// 	c.JSON(200, result)
	// 	return
	// }
	// if len(password) < 6 || len(password) > 30 {
	// 	result = response.Err(response.SERVER_ERROR, []string{"密码必须6-30不包含"})
	// 	c.JSON(200, result)
	// 	return
	// }
	//获取数据
	var user_service services.User
	if err := c.ShouldBindBodyWith(&user_service, binding.JSON); err != nil {
		result = response.Err(response.USER_REGISTER_ERR, []string{err.Error()})
		c.JSON(200, result)
		return
	}
	// data := map[string]string{"user_name": user_name, "password": password}
	data := user_service.Register()
	if !data {
		result = response.Err(response.USER_REGISTER_ERR, []string{"user register fail"})
		c.JSON(200, result)
		return
	}
	//返回结果集
	result = response.Sucess(data)
	c.JSON(200, result)
	return
}

func Login(c *gin.Context) {
	var result *response.Response
	var user_service services.User
	err := c.ShouldBindJSON(&user_service)
	if err != nil {
		result = response.Err(response.USER_LOGIN_ERR, []string{"绑定失败" + err.Error()})
		c.JSON(200, result)
		return
	}
	data, err := user_service.Login()
	if err != nil {
		result = response.Err(response.USER_LOGIN_ERR, []string{"登陆失败" + err.Error()})
		c.JSON(200, result)
		return
	}
	//返回结果集
	result = response.Sucess(data)
	c.JSON(200, result)
	return

}
